<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('新增参数')"/>
    <th:block th:include="include :: bootstrap-fileinput-css"/>
    <th:block th:include="include :: datetimepicker-css"/>
    <style>
        .file-input .theme-fas .file-input-ajax-new {
            width: 70%;
            margin-left: 150px;
        }

        .customselect {
            width: 16%;
            display: inline;
        }

        .custominput {
            width: 64%;
            display: inline;
            margin-left: 12px;
        }

        .opt {
            margin-left: 8px;
            background-color: #e5f3f2;
        }

        .row:not(:first-child) {
            margin-top: 12px;
        }

        .row {
            margin-left: -3px;
        }

    </style>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-config-add" name="form-config-add" enctype="multipart/form-data">
        <input type="hidden" id="progressId" name="progressId">

        <div class="form-group">
            <label class="col-sm-3 control-label">实际开始时间：</label>
            <div class="col-sm-8">
                <input type="text" class="form-control" id="actualStartTime" name="actualStartTime"
                       th:value="${progressplan.actualStartTime}" placeholder="yyyy-MM-dd" autocomplete="OFF">
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label">计划完成时间：</label>
            <div class="col-sm-8">
                <input style="margin-top: 7px;border:0px;outline:none;" id="planEndTime"
                       th:value="${progressplan.planEndTime}" readonly>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label">完成状态：</label>
            <div class="col-sm-8">
                <div class="radio check-box form-nofinish" id="nofinishDiv">
                    <label><input type="radio"  value="1" name="status" id="nofinish">未完成</label>
                </div>
                <div class="radio check-box">
                    <label><input type="radio" value="0" name="status" id="finish">完成</label>
                </div>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label">进度情况：</label>
            <div class="col-sm-8">

                <input style="margin-top: 7px;border:0px;outline:none;" id="progressDetail" name="progressDetail"
                       th:value="${progressplan.intervalDays}" readonly>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label">实际结束时间：</label>
            <div class="col-sm-8">
                <input type="text" class="form-control" id="actualEndTime" name="actualEndTime" placeholder="yyyy-MM-dd"
                       onchange="queryTime()"  autocomplete="off">
            </div>
        </div>

        <div class="form-group">
            <div style="width: 73%;margin-left: 130px">
                <label class="font-noraml">影像:</label>
                <div class="file-loading">
                    <input class="file" type="file" id="filePath" name="file" multiple data-min-file-count="1" data-theme="fas">
                </div>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label">描述详情：</label>
            <div class="col-sm-8">
                <div id="enuParam" class="param">
                </div>
            </div>
        </div>

    </form>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: bootstrap-fileinput-js"/>
<th:block th:include="include :: datetimepicker-js"/>
<script th:inline="javascript">

    // Init
    // 后台路由
    var prefix = ctx + "progressplan";

    // 初始化 计划完成时间隐藏
    // $("#actualEndTime").parents(".form-group").hide();

    // 初始化 获取服务端返回变量
    var progressId = [[${progressplan.progressId}]];
    $("#progressId").val([[${progressplan.progressId}]]);

    // 完成状态的回显
    if([[${progressplan.status}]] == '完成'){
        $("#finish").prop("checked",true);
        document.getElementById("nofinishDiv").style.display="none";
        $("#actualEndTime").parents(".form-group").show();
        $("#actualEndTime").val([[${progressplan.actualEndTime}]]);
    }else{
        $("#nofinish").prop("checked",true);
    }

    // 图片的回显
    var fileArr = new Array();
    fileArr.push([[${progressplan.virtualPath}]]);
    if (fileArr != '' || fileArr != null) {
        $('#filePath').fileinput({
            language: 'zh',                                        //语言
            uploadUrl: '<%=basePath%>/commodity/addCommodityPic',   //上传地址

            showPreview: true,				//展前预览
            showUpload: false,				//显示上传按钮
            showCaption: false,				//显示文字表述
            uploadAsync: false,                             //false 同步上传，后台用数组接收，true 异步上传，每次上传一个file,会调用多次接口
            removeFromPreviewOnError: true, //当选择的文件不符合规则时，例如不是指定后缀文件、大小超出配置等，选择的文件不会出现在预览框中，只会显示错误信息
            maxFileCount: 1,
            maxFileSize: 1024 * 10,			//单位为kb，如果为0表示不限制文件大小
            allowedFileExtensions: ["jpg", "jpeg", "gif", "png", "bmp", "pdf", "doc", "docx"],
            previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
            overwriteInitial: false,
            initialPreviewAsData: true,
            initialPreview: fileArr,
            initialPreviewConfig: [ //配置预览中的一些参数
                {
                    caption: "transport-1.jpg",
                    size: 329892,
                    width: "120px",
                    url: "deletePic",
                    // 注意: 1-progressId必填，用于图片物理路径的删除  2-key用于后台接收
                    key: progressId
                },
                {
                    caption: "transport-2.jpg",
                    size: 872378,
                    width: "120px",
                    url: "deletePic",
                    key: progressId
                }
            ]
        }).on('filepredelete', function (event, key, jqXHR, data) {
            console.log('Key = ' + key);
            console.log(jqXHR);
            console.log(data);
        });
    }

    // 初始化 格式化日期
    bindDatetimepicker();

    // 初始化 描述详情表单
    var enuParam_index = 1;
    $(function () {
        $("#reason").hide();
        // Case1 存在描述详情 初始化编辑页面
        if ([[${remarkList}]] != null) {
            // 显示展示框
            $("#reason").show();

            // 将数组格式的字符串转换成数组
            var arr = eval('(' + JSON.stringify([[${remarkList}]]) + ')');

            // 遍历数组初始化数据
            for (var i = 0; i < arr.length; i++) {
                var index = i + 1;
                var reasonType = arr[i].reasonType;
                var reasonTypeId = 'reasonType' + index;

                var enuParam = "<div id='enuParam_" + index + "' class='row'>" +
                    "<select id='reasonType" + index + "' name='progressplanDetail[" + index + "].reasonType' text=" + arr[i].reasonType + " class='form-control noselect2 customselect tt'>" +
                    "<option value='0'>人</option>" +
                    "<option value='1'>料</option>" +
                    "<option value='2'>机</option>" +
                    "<option value='3'>法</option>" +
                    "<option value='4'>环</option>" +
                    "<option value='5'>其他</option>" +
                    "</select>" +
                    "<input id='remark" + index + "' name='progressplanDetail[" + index + "].remark' placeholder='描述原因' value=" + arr[i].remark + " class='form-control custominput' autocomplete='off'>" +
                    "<span id='add' type='button' class='btn btn-sm opt'>+</span>" +
                    "<span onclick='del_enuParam(id)' id='del_enuParam_" + index + "' type='button' class='btn btn-sm opt'>-</span>" +
                    "</div>";
                $("#enuParam").append(enuParam);

                // 初始化select选中值
                var nums = $("#" + reasonTypeId).find("option"); //获取select下拉框的所有值
                for (var j = 1; j < nums.length; j++) {
                    if ($(nums[j]).text() == reasonType) {
                        $(nums[j]).prop('selected', 'selected');
                        break;
                    }
                }
            }
            // Case2 首次添加不存在存在描述详情 初始化编辑页面
        } else {
            var enuParam = "<div id='enuParam_" + enuParam_index + "' class='row'>" +
                "<select id='reasonType" + enuParam_index + "' name='progressplanDetail[" + enuParam_index + "].reasonType' class='form-control noselect2 customselect'>" +
                "<option value='0'>人</option>" +
                "<option value='1'>料</option>" +
                "<option value='2'>机</option>" +
                "<option value='3'>法</option>" +
                "<option value='4'>环</option>" +
                "<option value='5'>其他</option>" +
                "</select>" +
                "<input id='remark" + enuParam_index + "' name='progressplanDetail[" + enuParam_index + "].remark' placeholder='描述原因' class='form-control custominput' autocomplete='off'>" +
                "<span id='add' type='button' class='btn btn-sm opt'>+</span>" +
                "<span onclick='del_enuParam(id)' id='del_enuParam_" + enuParam_index + "' type='button' class='btn btn-sm opt'>-</span>" +
                "</div>";
            $("#enuParam").append(enuParam);
            enuParam_index++;
        }
    });

    // 初始化 存在详情添加按钮初始值
    if ([[${remarkList}]] != null) {
        var arr = eval('(' + JSON.stringify([[${remarkList}]]) + ')');
        var index_up = arr.length + 1;
    }

    // 初始化 不存在详情 添加按钮初始值
    var index_add = 2;

    // 添加按钮
    $(document).on("click", "#add", function () {
        // Case1 存在详情
        if ([[${remarkList}]] != null) {
            var enuParam = "<div id='enuParam_" + index_up + "' class='row'>" +
                "<select id='reasonType" + index_up + "' name='progressplanDetail[" + index_up + "].reasonType' class='form-control noselect2 customselect'>" +
                "<option value='0'>人</option>" +
                "<option value='1'>料</option>" +
                "<option value='2'>机</option>" +
                "<option value='3'>法</option>" +
                "<option value='4'>环</option>" +
                "<option value='5'>其他</option>" +
                "</select>" +
                "<input id='remark" + index_up + "' name='progressplanDetail[" + index_up + "].remark' placeholder='描述原因' class='form-control custominput' autocomplete='off'>" +
                "<span id='add' type='button' class='btn btn-sm opt'>+</span>" +
                "<span onclick='del_enuParam(id)' id='del_enuParam_" + index_up + "' type='button' class='btn btn-sm opt'>-</span>" +
                "</div>";
            $("#enuParam").append(enuParam);
            index_up++;
        } else {
            // Case2 不存在详情
            var enuParam = "<div id='enuParam_" + index_add + "' class='row'>" +
                "<select id='reasonType" + index_add + "' name='progressplanDetail[" + index_add + "].reasonType' class='form-control noselect2 customselect'>" +
                "<option value='0'>人</option>" +
                "<option value='1'>料</option>" +
                "<option value='2'>机</option>" +
                "<option value='3'>法</option>" +
                "<option value='4'>环</option>" +
                "<option value='5'>其他</option>" +
                "</select>" +
                "<input id='remark" + index_add + "' name='progressplanDetail[" + index_add + "].remark' placeholder='描述原因' class='form-control custominput' autocomplete='off'>" +
                "<span id='add' type='button' class='btn btn-sm opt'>+</span>" +
                "<span onclick='del_enuParam(id)' id='del_enuParam_" + index_add + "' type='button' class='btn btn-sm opt'>-</span>" +
                "</div>";
            $("#enuParam").append(enuParam);
            index_add++;
        }
    });

    // 删除按钮
    function del_enuParam(id) {
        var aa = id.split("_")
        var ids = aa[1] + "_" + aa[2]
        var enuParams = document.getElementById("enuParam")
        if (enuParams.childNodes.length > 2) {
            enuParams.removeChild(document.getElementById(ids))
        } else {
            layer.alert("至少保留一个");
        }
    }

    // 完成状态的切换 1-清空进度情况 2-计划完成时间(未完成:隐藏 完成:显示)
    $('input').on('ifChecked', function (event) {
        var value = $(event.target).val();
        // 未完成
        if (value == "1") {
            $("#progressDetail").val([[${progressplan.intervalDays}]])
            $("#actualEndTime").parents(".form-group").hide();
        } else {
            $("#progressDetail").val();
            $("#actualEndTime").val('');
            $("#actualEndTime").parents(".form-group").show();
        }
    });

    // 计划结束时间改变
    function queryTime() {
        var planEndTime = $("#planEndTime").val();
        var actualEndTime = $("#actualEndTime").val();

        var day = GetNumberOfDays(planEndTime, actualEndTime)
        if (day > 0) {
            var intervalDays = '滞后' + day + '天';
        }
        if (day == 0) {
            var intervalDays = '正常';
        }
        if (day < 0) {
            var intervalDays = '提前' + -day + '天';
        }
        $("#progressDetail").val(intervalDays)
    }

    // Called > 计算日期差
    function GetNumberOfDays(date1, date2) {
        //date1：开始日期，date2结束日期
        var a1 = Date.parse(new Date(date1));
        var a2 = Date.parse(new Date(date2));
        var day = parseInt((a2 - a1) / (1000 * 60 * 60 * 24));//核心：时间戳相减，然后除以天数
        return day
    };

    // Called > 格式化日期
    function bindDatetimepicker() {
        $("#actualStartTime").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true,
            language: 'zh-cn'
        });

        $("#actualEndTime").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true,
            language: 'zh-cn'
        });
    }

    /* 保存 */
    function submitHandler() {
        // 选择完成状态,实际结束时间必填
        if($('#finish').val() == '0'){
            if($('#actualEndTime').val() == '' || $('#actualEndTime').val() == null){
                $.modal.alertWarning("实际结束时间必填!")
                return;
            }
        }

        var reader = new FileReader()
        if($('#filePath')[0].files[0] != null){
            reader.readAsDataURL($('#filePath')[0].files[0])
            reader.onload = () => {
                if ($.validate.form()) {
                    var data = $("#form-config-add").serializeArray();
                    data.push({"name": "file", "value": reader.result});
                    $.operate.save(prefix + "/saveDetail", data);
                }
            }
        }else{
            var data = $("#form-config-add").serializeArray();
            data.push({"name": "file", "value": reader.result});
            $.operate.save(prefix + "/saveDetail", data);
        }
    }


</script>
</body>
</html>
